package zcj.stu.service;

import cn.hutool.crypto.digest.MD5;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import zcj.stu.Entity.Account;
import zcj.stu.dao.AccountDao;
import zcj.stu.dao.CommonDao;
import zcj.stu.utils.Constant;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Service
public class AccountService {
    @Resource
    private AccountDao accountDao;
    @Resource
    private CommonDao commonDao;
    private MD5 md5 = new MD5(Constant.ENCODE_SALT.getBytes(StandardCharsets.UTF_8));

    public Account ckLogin(Account account) {
        String username = account.getUsername();
        String password = new String(md5.digest(account.getPassword()));
        Query query = Query.query(Criteria.where("username").is(username)).addCriteria(Criteria.where("password").is(password));
        return accountDao.ckUAndP(query);
    }

    public boolean save(Account account) {
          account.setPassword(new String(md5.digest(account.getPassword())));
          return accountDao.save(account)!=null;
    }

    public boolean del(String id) {
        Query query = Query.query(Criteria.where("_id").is(id));
        return accountDao.del(query).getDeletedCount()>0;
    }

    public boolean edit(Account account) {
        Query query = Query.query(Criteria.where("_id").is(account.get_id()));
        Update update = new Update();
        update.set("username",account.getUsername());
        if(!StringUtils.isEmpty(account.getPassword())){
            update.set("password",new String(md5.digest(account.getPassword())));
        }
       return accountDao.edit(query,update).getModifiedCount()>0;
    }
}
